package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1. 得到当前请求的上下文对像
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2. 得到请求对象
        HttpServletRequest request = currentContext.getRequest();
        //3. 放行资源
        if (request.getMethod().equals("OPTIONS")){
            return null;
        }
        if (request.getRequestURI().equals("/login")) {
            return null;
        }
        //4. 得到请求头
        String header = request.getHeader("Authorization");
        System.out.println("header :" + header);
        //5. 判断请求头不为空
        if (StringUtils.isNotBlank(header) && header.startsWith("Bearer ")){
            //5.1 得到token
            String token = header.substring(7);
            System.out.println("token" + token);
            //5.2 解析token
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null){
             //5.3 得到roles
                String roles = (String) claims.get("roles");
                if (roles.equals("admin")){
                    currentContext.addZuulRequestHeader("Authorization",header);
                    System.out.println("将自己的请求头加到网关的请求头");
                    return null;
                }
            }
        }
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(403);
        currentContext.setResponseBody("无权xian访问");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
